package com.apobates.forum.grief.concurrent;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.beanutils.BeanUtils;

public interface CombineCollectionPromiseMapper<ID,T,V> {
    // Map Key
    // 组合对象toMap的Key映射
    Function<T, ID> keyMapper();
    // Attribute Name
    // 组合对象在值对象中的属性名
    String attrName();
    // 设置组合时从值对象中的Key映射
    Function<V,ID> valMapper();

    default BiFunction<Stream<V>, Stream<T>, Stream<V>> mapper(){
        return (voStms, cbStms)->{
            final Map<ID, T> cbMap = cbStms.collect(Collectors.toMap(keyMapper(), Function.identity()));
            return voStms.map(vo-> {
                T attrVal = cbMap.get(valMapper().apply(vo));
                try {
                    BeanUtils.setProperty(vo, attrName(), attrVal);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                return vo;
            });
        };
    };
}
